<template>
  <CardHead title="评估排名" :filters="filters" @onSelect="onSelect">
    <div class="w-full px-3 text-[#595959]">
      <div class="flex flex-col gap-3 rounded-lg bg-white p-4">
        <div v-if="!isLastLevel" class="flex items-center gap-2 mb-3">
          <template v-for="(typeTab, index) in typeTabs" :key="index">
            <p
              @click="() => (typeIndex = index)"
              :class="[currentType === typeTab.type ? 'text-yxt-blue' : 'text-[#595959]']"
            >
              {{ typeTab.name }}
            </p>
            <div
              v-if="index !== typeTabs.length - 1"
              class="w-[1px] h-[10px] bg-[#999999]"
            />
          </template>
        </div>
        <TeamCustomTavView :tabs="tabs" v-model:activeIndex="activeIndex" />
        <p class="text-[#BFBFBF] text-sm mt-5 mb-3">
          各部门完成情况如下，可点击查看具体明细
        </p>
        <ScoreProgress :progressItems="progressItems" @click="handleClickItem" />
      </div>
    </div>
  </CardHead>

  <van-action-sheet :title="currentItem?.label" v-model:show="showCompetencyPortrait">
    <CompetencyPortrait
      v-if="showCompetencyPortrait"
      :userId="currentItem.data.ssoUserId"
      :dept-id="currentItem.data.deptId"
    />
  </van-action-sheet>

  <van-action-sheet :title="currentItem?.label" v-model:show="showTaskCompletion">
    <TaskCompletion
      v-if="showTaskCompletion"
      :userId="currentItem.data.ssoUserId"
      :dept-id="currentItem.data.deptId"
    />
  </van-action-sheet>
</template>

<script setup lang="ts">
import CardHead from "@/views/myXmate/myTeam/components/cardHead.vue";
import { FilterItem, FilterOptions } from "@/views/myXmate/myTeam/components/cardHead";
import TeamCustomTavView from "@/views/myXmate/myTeam/components/teamCustomTavView.vue";
import { TabItem } from "@/views/myXmate/myTeam/components/teamCustomTavView.d";
import ScoreProgress from "@/views/myXmate/components/scoreProgress.vue";
import CompetencyPortrait from "./competencyPortrait.vue";
import TaskCompletion from "./taskCompletion.vue";
import {
  EvaluationRankingParams,
  RankModel,
  getRankScoresAPI,
  TargetType,
  ReportDataType,
  ReportType,
} from "@/services/myXmate";
import { useMyXmateStore } from "@/store";
import { computed, ComputedRef, onMounted, Ref, ref, watch } from "vue";
import reportOptions from "../reportOptions.json";
import { getUserInfo } from "@/utils/auth";
import { formatCompletionTime, ParameterDateType } from "@/utils/timeTool";
const store = useMyXmateStore();

onMounted(() => {
  getData();
});

const assessmentSettings = computed(() => store.assessmentSettings);
function mapSystemTab(v: any) {
  const { customizedAssessments, systemAssessments } = v;
  const arr = [...systemAssessments, ...customizedAssessments];
  arr.unshift({
    name: "全部维度",
    id: "all",
  });
  return arr.map((item) => {
    const { name, id } = item;
    return {
      text: name,
      value: id,
    };
  });
}

const typeIndex = ref(0);
const currentType = computed(() => typeTabs.value[typeIndex.value].type);
const typeTabs = computed(() => {
  return isLastLevel.value
    ? [{ name: "成员", type: TargetType.USER }]
    : [
        { name: "团队", type: TargetType.DEPLOYMENT },
        { name: "成员", type: TargetType.USER },
      ];
});

const taskTabs = computed(() => {
  return mapSystemTab(assessmentSettings.value?.taskCompleteAssesses);
});

const salesAbilityTab = computed(() => {
  return mapSystemTab(assessmentSettings.value?.salesAbilityAssesses);
});

const activeIndex = ref(0);
const tabs: ComputedRef<TabItem[] | null> = computed(() => {
  if (!assessmentSettings.value) return [];
  if (currentFilter.value?.value === ReportDataType.ABILITY) {
    return salesAbilityTab.value;
  }
  return taskTabs.value;
});

const currentDeptId = computed(() => store.noticeBoardPublicParam.currentDept?.id);
const reportType = computed(() => store.noticeBoardPublicParam.reportType);
const startTime = computed(() => store.noticeBoardPublicParam.startDate);
const endTime = computed(() => store.noticeBoardPublicParam.endDate);
const isLastLevel = computed(() => store.isLastLevelDepartment);
const dimensionId = computed(() => tabs.value[activeIndex.value]?.value);
const userOrDeparment = computed(() => currentType.value);

// 销售表现
const currentFilter: Ref<FilterOptions> = ref(reportOptions[0]);
const filters = [
  {
    text: currentFilter.value?.text,
    type: currentFilter.value?.value,
    options: reportOptions,
  },
];

watch([currentDeptId, reportType, dimensionId, userOrDeparment], () => {
  if (isLastLevel.value) {
    typeIndex.value = 0;
  }
  getData();
});

const makeParam = () => {
  let param: EvaluationRankingParams = {
    orgId: getUserInfo().orgId,
    deptId: currentDeptId.value,
    userOrDeparment: userOrDeparment.value,
    dataType: currentFilter.value?.value as ReportDataType,
    dimensionId: dimensionId.value as string,
    params: {
      startTime: formatCompletionTime(startTime.value, ParameterDateType.START_DATE),
      endTime: formatCompletionTime(endTime.value, ParameterDateType.ENE_DATE),
      reportType: reportType.value as ReportType,
    },
  };
  console.log("makeParam: ", param);

  return param;
};

const dataList: Ref<RankModel[]> = ref([]);
const getData = async () => {
  if (!assessmentSettings.value) {
    await store.getAssessmentSettingsAction();
  }
  const data = await getRankScoresAPI(makeParam());
  dataList.value = data.datas;
};

const onSelect = (filterItem: FilterItem) => {
  const { options } = filterItem;
  currentFilter.value = options?.find(
    (temp: FilterOptions) => temp.value === filterItem.value
  );
  getData();
};

const progressItems = computed(() => {
  let total = dataList.value.reduce((sum, item) => {
    return sum + (item.score || 0);
  }, 0);

  let average = 0;
  if (total > 0) {
    average = total / dataList.value.length;
  }
  return {
    averageSource: average.toFixed(2),
    unit: currentFilter.value?.value === ReportDataType.ABILITY ? "" : "%",
    list: dataList.value.map((v) => {
      console.log("progressItems: ", v);
      return {
        label: v.name || v.deptName,
        value: v.score?.toFixed(2) || 0,
        data: v,
        unit: currentFilter.value?.value === ReportDataType.ABILITY ? "" : "%",
      };
    }),
  };
});

const showCompetencyPortrait = ref(false);
const showTaskCompletion = ref(false);
const currentItem = ref();
function handleClickItem(v: any) {
  if (currentType.value === TargetType.DEPLOYMENT) {
    return;
  }
  currentItem.value = v;
  console.log("handleClickItem: ", v, currentFilter.value?.value);
  if (currentFilter.value?.value === ReportDataType.ABILITY) {
    showTaskCompletion.value = false;
    showCompetencyPortrait.value = true;
  } else {
    showTaskCompletion.value = true;
    showCompetencyPortrait.value = false;
  }
}
</script>
